package com.fhz.worktest

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.work.*
import java.util.concurrent.TimeUnit
import kotlin.concurrent.thread

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        //workmanager
        /**
         * 后台持续处理任务
         *
         * 1,work
         * 2,workrequest
         *  2.1 一次oneTime
         *  2.2 重复执行,时间间隔最少15分钟.
         * 3,workmanager
         *
         */

         // 协程
        //子线程


        //约束
        val constraints = Constraints.Builder()
            .setRequiredNetworkType(NetworkType.UNMETERED)
            .setRequiresCharging(true)
            .build()


        //只会执行一次
        val oneTimeRequest = OneTimeWorkRequest.Builder(SimpleWorker::class.java)
            .setInitialDelay(5,TimeUnit.SECONDS)
            .addTag("简单任务")
            .setBackoffCriteria(BackoffPolicy.LINEAR,10,TimeUnit.SECONDS)
            .setConstraints(constraints)
            .build()


        val oneTimeRequest1 = OneTimeWorkRequest.Builder(SimpleWorker::class.java)
            .setInitialDelay(5,TimeUnit.SECONDS)
            .addTag("简单任务")
            .build()

        //重复执行. 一直执行.知道调用cancal
        val request = PeriodicWorkRequest.Builder(SimpleWorker::class.java, 15, TimeUnit.MINUTES).build()





        WorkManager.getInstance(this).enqueue(oneTimeRequest)

//        WorkManager.getInstance(this)
//            .beginWith(oneTimeRequest)
//            .then(oneTimeRequest1)
//            .enqueue()


        WorkManager.getInstance(this).getWorkInfoByIdLiveData(oneTimeRequest.id)
            .observe(this) { workInfo ->
                if (workInfo.state == WorkInfo.State.SUCCEEDED) {
//                    Log.d("MainActivity", "do work succeeded")
                    println("successed")

                } else if (workInfo.state == WorkInfo.State.FAILED) {
//                    Log.d("MainActivity", "do work failed")
                    println("failed")
                }
            }

//        WorkManager.getInstance(this).cancelAllWorkByTag("简单任务")
//        WorkManager.getInstance(this).cancelWorkById(oneTimeRequest.id)
//        WorkManager.getInstance(this).cancelWorkById(oneTimeRequest1.id)
//



    }


}